import deviceAddHtml from '../../assets/partials/device-add.html'

$.addDevice = function addDevice(deviceType) {
    let groupId = $('#tree-panel').find(".selected").attr("data-id");
    if (groupId == undefined) {
        alert("请在左边分组栏选择一个分组");
        return;
    }
    $.dialog({
        title: "导入设备",
        message: function(dialog) {
            let $content = $("<div>").html(deviceAddHtml);
            if (deviceType != undefined) {
                let $input = $content.find("input[name='deviceType']");
                $input.removeClass("hidden");
                $input.val(deviceType);
                switch (deviceType) {
                    case "SERVER":
                        break;
                    case "STB":
                        $content.find("#room").removeClass("hidden");
                        break;
                }
            } else {
                $content.find("select[name='deviceType']").removeClass("hidden");
            }
            $.myAjax({
                url: "group/getAllGroup.do",
                success: function(res) {
                    if (res.data.length != 0) {
                        var $options = [];
                        $.each(res.data, function(index, item) {
                            var option = $("<option>").text(item.name).val(item.id);
                            if (groupId == item.id) {
                                option.attr("selected", true);
                            } else if (groupId == undefined && item.lvl == 1) {
                                option.attr("selected", true);
                            }
                            $options.push(option);
                        });
                        $content.find("select[name='groupId']").append($options);
                    }
                }
            });
            return $content
        },
        submit: function(dialog) {
            let body = dialog.getModalBody()[0];
            let params = $(body).find("form").serializeArray();
            let data = {}
            for (let x in params) {
                data[params[x].name] = params[x].value;
            }
            $.myAjax({
                url: "device/addDevice.do",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function(res) {
                    dialog.close();
                    var table = $(".table").DataTable();
                    table.draw();
                }
            });
        }
    });
}
